package com.huiminpay.merchant.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.exception.BizException;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.merchant.convert.AppConvert;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.mapper.AppMapper;
import com.huiminpay.merchant.service.IAppService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author 王帅坤
 * @date 2021年06月07日16:48
 */
@Service
public class AppServiceImpl implements IAppService {

    @Autowired
    private AppMapper appMapper;
    @Override
    public AppDTO findAppById(Long id) {
        App app = appMapper.selectById(id);
        AppDTO appDto = new AppDTO();
        BeanUtils.copyProperties(app,appDto);
        return appDto;
    }

    @Override
    public AppDTO createApp(AppDTO appDTO) throws BizException {
        //1.名称唯一校验
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getAppName,appDTO.getAppName());
        Integer count = appMapper.selectCount(qw);
        if (count>0){
            throw new BizException(CommonErrorCode.E_100006);
        }

//        1.1对象转换
        App app = AppConvert.INSTANCE.dto2entity(appDTO);
        //2.设置appid使用UUID
        app.setAppId(RandomUuidUtil.getUUID());
        //3.保存数据库
        appMapper.insert(app);
        return AppConvert.INSTANCE.entity2dto(app);
    }

    @Override
    public List<AppDTO> queryApps(Long merchantId) {
        //App app = new App();
        //app.setMerchantId(merchantId);

        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getMerchantId,merchantId);
        List<App> apps = appMapper.selectList(qw);
        return AppConvert.INSTANCE.entityList2dtoList(apps);
    }

    @Override
    public AppDTO updateApp(AppDTO appDTO) throws BizException{

        // 1. 名称唯一校验
        QueryWrapper<App> qw = new QueryWrapper<>();
        qw.lambda().eq(App::getAppName,appDTO.getAppName());
        Integer integer = appMapper.selectCount(qw);
        if(integer>0){
            throw new BizException(CommonErrorCode.E_100006);
        }
        //1对象转换
        App app = AppConvert.INSTANCE.dto2entity(appDTO);
        UpdateWrapper<App> uw = new UpdateWrapper<>();
        uw.lambda().eq(App::getAppId,app.getAppId());
        appMapper.update(app,uw);

        return AppConvert.INSTANCE.entity2dto(app);
    }
}
